package top.hcode.hoj.controller.coll;

import java.util.List;
import java.util.stream.Collectors;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.nutz.lang.Lang;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import top.hcode.hoj.common.result.CommonResult;
import top.hcode.hoj.manager.coll.ItechCollCreatedWorksManager;
import top.hcode.hoj.manager.coll.ItechCollHonorRecordManager;
import top.hcode.hoj.manager.coll.ItechCollQuestionManager;
import top.hcode.hoj.manager.coll.ItechCollSelfIntroManager;
import top.hcode.hoj.manager.coll.ItechCollTrainingRecordManager;
import top.hcode.hoj.pojo.dto.BaseIdDTO;
import top.hcode.hoj.pojo.dto.coll.CollQuestionAnswerDTO;
import top.hcode.hoj.pojo.dto.coll.CollStartAnswerDTO;
import top.hcode.hoj.pojo.dto.coll.CollSubmitQuestionAnswerBatchDTO;
import top.hcode.hoj.pojo.dto.coll.QueryCollQuestionDTO;
import top.hcode.hoj.pojo.dto.coll.QueryCollUserAnswerStatusDTO;
import top.hcode.hoj.pojo.dto.coll.SaveCollTrainingRecordDTO;
import top.hcode.hoj.pojo.dto.coll.SaveSelfIntroDTO;
import top.hcode.hoj.pojo.entity.coll.CollCreatedWorks;
import top.hcode.hoj.pojo.entity.coll.CollHonorRecord;
import top.hcode.hoj.pojo.entity.coll.CollSelfIntro;
import top.hcode.hoj.pojo.entity.coll.CollTrainingRecord;
import top.hcode.hoj.pojo.entity.coll.ItechCollection;
import top.hcode.hoj.pojo.vo.coll.CollCreatedWorksVO;
import top.hcode.hoj.pojo.vo.coll.CollQuestionUserAnswerStatusVO;
import top.hcode.hoj.pojo.vo.coll.CollQuestionVO;
import top.hcode.hoj.service.RateLimitService;
import top.hcode.hoj.service.admin.AdminItechCollectionService;
import top.hcode.hoj.utils.Constants;
import top.hcode.hoj.utils.ShiroUtils;

/**
 * @author orangej
 * @since 2025/1/21
 */
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Api(tags = "信息技术摸底采集接口")
public class ItechCollectionController {

    private final AdminItechCollectionService itechCollectionService;
    private final ItechCollSelfIntroManager selfIntroManager;
    private final ItechCollTrainingRecordManager trainingRecordManager;
    private final ItechCollHonorRecordManager honorRecordManager;
    private final ItechCollCreatedWorksManager createdWorksManager;
    private final ItechCollQuestionManager questionManager;

    private final RateLimitService rateLimitService;
    
    // 查询当前活动
    @GetMapping("/itech-coll/list")
    @ApiOperation(value = "获取信息技术摸底采集活动")
    @ApiOperationSupport(order = 5)
    @RequiresAuthentication
    public CommonResult<List<ItechCollection>> getItechCollList() {
        String userId = ShiroUtils.getUid();
        return CommonResult.successResponse(itechCollectionService.queryValidItechCollectionList(userId));
    }

    //    个人介绍 start
    @PostMapping("/itech-coll/self-intro/save")
    @ApiOperation(value = "保存个人介绍")
    @ApiOperationSupport(order = 10)
    @RequiresAuthentication
    public CommonResult<CollSelfIntro> saveSelfIntro(@Validated @RequestBody SaveSelfIntroDTO dto) {
        String uid = ShiroUtils.getUid();
        CollSelfIntro dbo = selfIntroManager.saveSelfIntro(uid, Constants.DEFAULT_COLL_ID, dto.getContent());
//        userStatService.updateUserSelfIntroCount(uid, Constants.DEFAULT_COLL_ID, 1);
        return CommonResult.successResponse(dbo);
    }

    @GetMapping("/itech-coll/self-intro/get")
    @ApiOperation(value = "获取个人介绍")
    @ApiOperationSupport(order = 20)
    @RequiresAuthentication
    public CommonResult<CollSelfIntro> getSelfIntro() {
        String uid = ShiroUtils.getUid();
        String collId = Constants.DEFAULT_COLL_ID;
        return CommonResult.successResponse(selfIntroManager.getSelfIntro(uid, collId));
    }

    @PostMapping("/itech-coll/self-intro/delete")
    @ApiOperation(value = "删除个人介绍")
    @ApiOperationSupport(order = 30)
    @RequiresAuthentication
    public CommonResult<Void> deleteSelfIntro() {
        String uid = ShiroUtils.getUid();
        String collId = Constants.DEFAULT_COLL_ID;
        CollSelfIntro dbo = selfIntroManager.deleteSelfIntro(uid, collId);

        if (dbo != null) {
//            userStatService.updateUserSelfIntroCount(uid, Constants.DEFAULT_COLL_ID, 0);
        }

        return CommonResult.successResponse();
    }
    /* 个人介绍 end */

    /* 学习经历 start */
    @PostMapping("/itech-coll/training-record/save")
    @ApiOperation(value = "保存学习经历")
    @ApiOperationSupport(order = 40)
    @RequiresAuthentication
    public CommonResult<List<CollTrainingRecord>> saveTrainingRecord(@Validated @RequestBody List<SaveCollTrainingRecordDTO> records) {
        if (Lang.isEmpty(records)) {
            return CommonResult.errorResponse("学习经历不能为空！");
        }

        String uid = ShiroUtils.getUid();
        String collId = Constants.DEFAULT_COLL_ID;

        records.forEach(record -> {
            record.setUserId(uid);
            record.setCollId(collId);
        });

        List<CollTrainingRecord> result = trainingRecordManager.saveTrainingRecord(records);
//        userStatService.updateUserTrainingRecordCount(uid, Constants.DEFAULT_COLL_ID, records.size());

        return CommonResult.successResponse(result);
    }

    @GetMapping("/itech-coll/training-record/list")
    @ApiOperation(value = "获取学习经历")
    @ApiOperationSupport(order = 50)
    @RequiresAuthentication
    public CommonResult<List<CollTrainingRecord>> getTrainingRecordList() {
        String uid = ShiroUtils.getUid();
        String collId = Constants.DEFAULT_COLL_ID;
        return CommonResult.successResponse(trainingRecordManager.getTrainingRecordList(uid, collId));
    }

    @PostMapping("/itech-coll/training-record/delete")
    @ApiOperation(value = "删除学习经历")
    @ApiOperationSupport(order = 60)
    @RequiresAuthentication
    public CommonResult<Void> deleteTrainingRecord(@Validated @RequestBody BaseIdDTO dto) {
        String uid = ShiroUtils.getUid();
        CollTrainingRecord dbo = trainingRecordManager.deleteTrainingRecord(uid, dto.getId());
        if (dbo != null) {
//            userStatService.updateUserTrainingRecordCount(uid, Constants.DEFAULT_COLL_ID,
//                    trainingRecordManager.countTrainingRecord(uid, Constants.DEFAULT_COLL_ID));
        }

        return CommonResult.successResponse();
    }
    // 学习经历 end

    // 荣誉奖项 start
    @PostMapping("/itech-coll/honor-record/save")
    @ApiOperation(value = "保存荣誉奖项")
    @ApiOperationSupport(order = 70)
    @RequiresAuthentication
    public CommonResult<CollHonorRecord> saveHonorRecord(@Validated @RequestBody CollHonorRecord record) {
        String uid = ShiroUtils.getUid();
        String collId = Constants.DEFAULT_COLL_ID;
        record.setUserId(uid);
        record.setCollId(collId);
        record = honorRecordManager.saveHonorRecord(record);

        // int count = honorRecordManager.countHonorRecord(uid, collId);
//        userStatService.updateUserHonorRecordCount(uid, Constants.DEFAULT_COLL_ID, count);
        return CommonResult.successResponse(record);
    }

    @GetMapping("/itech-coll/honor-record/list")
    @ApiOperation(value = "获取荣誉奖项")
    @ApiOperationSupport(order = 80)
    @RequiresAuthentication
    public CommonResult<List<CollHonorRecord>> getHonorRecordList() {
        String uid = ShiroUtils.getUid();
        String collId = Constants.DEFAULT_COLL_ID;
        return CommonResult.successResponse(honorRecordManager.getHonorRecordList(uid, collId));
    }

    @PostMapping("/itech-coll/honor-record/delete")
    @ApiOperation(value = "删除荣誉奖项")
    @ApiOperationSupport(order = 90)
    @RequiresAuthentication
    public CommonResult<Void> deleteHonorRecord(@Validated @RequestBody BaseIdDTO dto) {
        String uid = ShiroUtils.getUid();
        CollHonorRecord dbo = honorRecordManager.deleteHonorRecord(uid, dto.getId());
        if (dbo != null) {
            // int count = honorRecordManager.countHonorRecord(uid, Constants.DEFAULT_COLL_ID);
//            userStatService.updateUserHonorRecordCount(uid, Constants.DEFAULT_COLL_ID, count);
        }
        return CommonResult.successResponse();
    }
    /* 荣誉奖项 end */

    /* 作品集 start */
    @PostMapping("/itech-coll/created-works/save")
    @ApiOperation(value = "保存作品集")
    @ApiOperationSupport(order = 100)
    @RequiresAuthentication
    public CommonResult<CollCreatedWorksVO> saveCreatedWorks(@Validated @RequestBody CollCreatedWorks dto) {
        String uid = ShiroUtils.getUid();
        String collId = Constants.DEFAULT_COLL_ID;
        dto.setUserId(uid);
        dto.setCollId(collId);
        CollCreatedWorks dbo = createdWorksManager.saveCreatedWorks(dto);

//        userStatService.updateCreateWorksCount(uid, collId, 1);

        // 返回详情
        return CommonResult.successResponse(createdWorksManager.getCreatedWorksDetail(dbo.getId()));
    }

    @GetMapping("/itech-coll/created-works/get")
    @ApiOperation(value = "获取作品集")
    @ApiOperationSupport(order = 110)
    @RequiresAuthentication
    public CommonResult<CollCreatedWorksVO> getCreatedWorks() {
        String uid = ShiroUtils.getUid();
        String collId = Constants.DEFAULT_COLL_ID;
        return CommonResult.successResponse(createdWorksManager.getCreatedWorksDetail(uid, collId));
    }

    @PostMapping("/itech-coll/created-works/delete")
    @ApiOperation(value = "删除作品集")
    @ApiOperationSupport(order = 120)
    @RequiresAuthentication
    public CommonResult<Void> deleteCreatedWorks(@Validated @RequestBody BaseIdDTO dto) {
        String uid = ShiroUtils.getUid();
        CollCreatedWorks dbo = createdWorksManager.deleteCreatedWorks(uid, dto.getId());
        if (dbo != null) {
//            userStatService.updateCreateWorksCount(uid, Constants.DEFAULT_COLL_ID, 0);
        }
        return CommonResult.successResponse();
    }
    // 作品集 end

    // 客观题 start
    @GetMapping("/itech-coll/question/list")
    @ApiOperation(value = "获取客观题")
    @ApiOperationSupport(order = 130)
    @RequiresAuthentication
    public CommonResult<List<CollQuestionVO>> queryQuestionList(@Validated QueryCollQuestionDTO dto) {
        if (dto == null) {
            dto = new QueryCollQuestionDTO();
        }
        if (dto.getCollId() == null) {
            dto.setCollId(Constants.DEFAULT_COLL_ID);
        }
        return CommonResult.successResponse(questionManager.queryQuestionList(dto));
    }

    @GetMapping("/itech-coll/question/detail")
    @ApiOperation(value = "获取题目详情", notes = "获取题目详情，包括选项列表")
    @ApiOperationSupport(order = 140)
    @RequiresAuthentication
    public CommonResult<CollQuestionVO> getQuestionDetail(@Validated BaseIdDTO dto) {
        return CommonResult.successResponse(questionManager.getQuestionDetail(String.valueOf(dto.getId())));
    }

    @PostMapping("/itech-coll/question/answer/start")
    @ApiOperation(value = "开始答题")
    @ApiOperationSupport(order = 150)
    @RequiresAuthentication
    public CommonResult<CollQuestionUserAnswerStatusVO> startAnswer(@Validated @RequestBody CollStartAnswerDTO dto) {
        String uid = ShiroUtils.getUid();
        questionManager.startAnswer(uid, dto.getCollId());
        return CommonResult.successResponse(questionManager.getUserAnswerStatus(uid, dto.getCollId()));
    }

    @PostMapping("/itech-coll/question/answer/submit-batch")
    @ApiOperation(value = "提交客观题答案（所有题目）")
    @ApiOperationSupport(order = 160)
    @RequiresAuthentication
    public CommonResult<String> submitSolution(@RequestBody CollSubmitQuestionAnswerBatchDTO dto) {
        if (!rateLimitService.tryAcquireSubmitAnswerBatch()) {
            return CommonResult.successResponse("busy");
        }

        String uid = ShiroUtils.getUid();

        // 提交答案
        questionManager.submitAnswer(uid, dto.getCollId(), dto.getQuestionAnswerList());

        // 成功提交
        return CommonResult.successResponse("ok");
    }

    @GetMapping("/itech-coll/question/user-answer-status")
    @ApiOperation(value = "获取学生答题情况", notes = "返回学生已经做过的题目id")
    @ApiOperationSupport(order = 170)
    @RequiresAuthentication
    public CommonResult<CollQuestionUserAnswerStatusVO> getUserAnswerStatus(@Validated QueryCollUserAnswerStatusDTO dto) {
        String uid = ShiroUtils.getUid();
        return CommonResult.successResponse(questionManager.getUserAnswerStatus(uid, dto.getCollId()));
    }

    @GetMapping("/itech-coll/question/test-submit-rps")
    public CommonResult<Void> testSubmitRps() {
        String uid = ShiroUtils.getUid();

        // 提交答案
        List<CollQuestionAnswerDTO> answerList = testQuestionIdList.stream().map(questionId -> {
            CollQuestionAnswerDTO dto = new CollQuestionAnswerDTO();
            dto.setQuestionId(questionId);
            dto.setAnswer(questionId);
            return dto;
        }).collect(Collectors.toList());
        questionManager.submitAnswer(uid, Constants.DEFAULT_COLL_ID, answerList);

        return CommonResult.successResponse();
    }

    @GetMapping("/itech-coll/echo")
    public CommonResult<String> echo() {
        return CommonResult.successResponse("ok");
    }

    private static List<String> testQuestionIdList = Lang.list("1888424281491222529", "1889333866078937089", "1889333869509877761", "1889333869958668289", "1889333870592008193", "1889333872437501954", "1889333873007927298", "1889333875289628673", "1889333876241735682", "1889333876690526209", "1889333877198036994", "1889333877709742082", "1889333878225641473", "1889333878800261121", "1890706439073173506", "1890399155780636674", "1890399554742833153", "1890400238200475650", "1890400468023169025", "1890707848795525122", "1890708238521864193", "1890708529635921922", "1890708790139949057", "1890709168097071105", "1890709381561978882", "1890400919745515522");
    // 客观题 end
}
